<?php

namespace App\Repositories;


abstract class Repository implements RepositoryInterface {

	protected $model;

	protected $order = array();

	/**
	 * 查询条件
	 * @param array $condition
	 * @return $this
	 */
	public function condition($condition) {
		if (method_exists($this, 'SearchCondition')) {
			$condition = $this->SearchCondition($condition);
		}
		if (!empty($condition)) {
			foreach ($condition as $k => $v) {
				if (!empty($v)) {
					if (is_array($v)) {
						if (strtolower($v[0]) == 'in') {
							// in 查询
							$this->model = $this->model->whereIn($k, $v[1]);
						} else {
							//普通条件查询 如：like < > <= >=
							$this->model = $this->model->where($k, $v[0], $v[1]);
						}
					} else {
						//普通相等查询
						$this->model = $this->model->where($k, $v);
					}
				}

			}
		}
		return $this;
	}

	/**
	 * 排序
	 * @param $order
	 */
	public function order($order) {
		if (is_array($order) && !empty($order)) {
			$this->model = $this->model->orderBy($order[0], $order[1]);
		}
	}

	/**
	 * 查询所有记录
	 * @param array $field
	 * @param array $order
	 * @return mixed
	 */
	public function all($field = array('*'), $order = array()) {
		$this->order($order ? $order : $this->order);
		return $this->model->get($field);
	}

	/**
	 * 查询分页记录
	 * @param int   $page
	 * @param array $order
	 * @return mixed
	 */
	public function paginate($page = 15, $order = array()) {
		$this->order($order ? $order : $this->order);
		return $this->model->paginate($page);
	}

	/**
	 * 添加一条记录
	 * @param array $data
	 * @return mixed
	 */
	public function create(array $data) {
		return $this->model->create($data);
	}

	/**
	 * 更新一条记录
	 * @param array  $data
	 * @param        $id
	 * @param string $attribute
	 * @return mixed
	 */
	public function update(array $data, $id, $attribute = "id") {
		return $this->model->where($attribute, $id)->update($data);

	}

	/**
	 * 删除一条记录
	 * @param        $id
	 * @param string $attribute
	 * @return mixed
	 */
	public function delete($id, $attribute = "id") {
		return $this->model->where($attribute, $id)->delete();
	}

	/**
	 * 查找一条记录
	 * @param       $id
	 * @param array $field
	 */
	public function find($id, $field = array('*')) {
		return $this->model->find($id, $field);
	}

	/**
	 * 通过 $field 查找一条记录
	 * @param       $field
	 * @param       $value
	 * @param array $columns
	 * @return mixed
	 */
	public function findBy($field, $value, $columns = array('*')) {
		return $this->model->where($field, $value)->first($columns);
	}
}
